package com.atguigu.lease.web.admin.service.impl;
import com.atguigu.lease.common.minioProperties.MinioMyProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioMyProperties myProperties;
    /*
     * 这里注入进来相当于把SpringBoot自带的MinioClient对象注入进来
     * 到时候直接调用自带的就可以，不然还得每次调用里面的启动方法很麻烦
     */
    @Autowired
    private MinioClient myMioioClient;


    @Override
    @SneakyThrows
    public String upLoadFile(MultipartFile file) {

        //创建桶
        boolean exists = myMioioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(myProperties.getBucketName())
                .build());
        if (!exists) {
            myMioioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(myProperties.getBucketName())
                    .build());
            System.out.println("创建桶成功!");
            myMioioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .config(myProperties.getPolicy())
                    .build());
            System.out.println("自定义权限添加成功!");
        }

        //文件名定义  SimpleDateFormat格式化年月日的格式 目的:  防止文件重名
        String fileName =
                new SimpleDateFormat("yyyy-MM-dd")
                        .format(new Date()) + "/" + UUID.randomUUID().toString() + "-"+file.getOriginalFilename();

        //上传照片
        myMioioClient.putObject(PutObjectArgs.builder()
                .bucket(myProperties.getBucketName())
                //文件名
                .object(fileName)
                //文件的类型
                .contentType(file.getContentType())
                //判断文件的大小,进行拆包转发
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());

        //url拼接是为了给前端一个地址用于预览和下载
        String url = String.join("/", myProperties.getEndPoint(), myProperties.getBucketName(), fileName);
        return url;

    }
}
